package com.rc.saas.tenant.job;

import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.redis.RedisDao;
import com.rc.saas.tenant.common.utils.DateUtil;
import com.rc.saas.tenant.model.operator.*;
import com.rc.saas.tenant.model.order.OrderInfo;
import com.rc.saas.tenant.model.order.OrderInfoExample;
import com.rc.saas.tenant.model.rc.RcOperatorAccount;
import com.rc.saas.tenant.model.rc.RcOperatorAccountExample;
import com.rc.saas.tenant.model.operator.RcOperatorExample;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.service.rc.RcOperatorAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.util.*;

/**
 * 加盟商结算-定时任务
 */
public class RcOperatorAccountServiceTask {

    Logger logger = LoggerFactory.getLogger(RcOperatorAccountServiceTask.class);

    @Autowired
    private RcOperatorService rcOperatorService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RcOperatorAccountService rcOperatorAccountService;

    @Autowired
    private RedisDao redisDao;

    @Autowired
    private UidGenerator uidGenerator;

    public void run() {
        long start = System.currentTimeMillis();
        try {
            if(!redisDao.setIfAbsent(getClass().getName(),"1",60*1000)){
                logger.info("----加盟商结算-定时任务----正在执行...");
                return;
            }
            logger.info("----加盟商结算-定时任务----开始执行");
            //查询加盟商列表
            RcOperatorExample operatorExample = new RcOperatorExample();
            operatorExample.createCriteria().andStatusEqualTo("0").andApplyStatusEqualTo("1");
            List<RcOperator> rcOperatorList = rcOperatorService.selectByExample(operatorExample);
            if(CollectionUtils.isEmpty(rcOperatorList)){
                //加盟商列表为空，返回
                return;
            }
            //遍历加盟商，分别结算月度订单
            for (RcOperator operator:rcOperatorList) {
                OrderInfoExample orderInfoExample = new OrderInfoExample();
                orderInfoExample.createCriteria().andOperatorIdEqualTo(operator.getOperatorId())
                        .andStatusIn(Arrays.asList(String.valueOf('2'),String.valueOf('4')))
                        .andOccupyPayTimeBetween(DateUtil.getLastMonthStart(),DateUtil.getLastMonthEnd());
                List<OrderInfo> orderInfoList = orderInfoService.selectByExample(orderInfoExample);
                if(CollectionUtils.isEmpty(orderInfoList)){
                    //订单为空，跳过
                    continue;
                }
                //汇总实付金额
                BigDecimal amountTotal = BigDecimal.ZERO;
                for (OrderInfo orderInfo : orderInfoList) {
                    if(Objects.isNull(orderInfo) || Objects.isNull(orderInfo.getPayAmount())){
                        continue;
                    }
                    amountTotal = amountTotal.add(orderInfo.getPayAmount());
                }
                RcOperatorAccount operatorAccount = null;
                RcOperatorAccountExample operatorAccountExample = new RcOperatorAccountExample();
                operatorAccountExample.createCriteria().andOperatorIdEqualTo(operator.getOperatorId())
                        .andMonthEqualTo(DateUtil.format(DateUtil.getLastMonthStart(),DateUtil.DATE_MONTH_FORMAT));
                List<RcOperatorAccount> operatorAccountList = rcOperatorAccountService.selectByExample(operatorAccountExample);
                if(!CollectionUtils.isEmpty(operatorAccountList)){
                    for (RcOperatorAccount roa : operatorAccountList) {
                        if("0".equals(roa.getStatus())){
                            operatorAccount = roa;
                        }
                        if("1".equals(roa.getStatus())){
                            return;
                        }
                    }
                }
                if(Objects.isNull(operatorAccount)){
                    operatorAccount = new RcOperatorAccount(operator.getOperatorId(), operator.getTenantCode(),
                            operator.getOperatorName(), operator.getPhone(), operator.getContactName(), uidGenerator.genBillOrderNum(operator.getTenantCode(),System.currentTimeMillis()>>16),
                            amountTotal, DateUtil.format(DateUtil.getLastMonthStart(),DateUtil.DATE_MONTH_FORMAT));
                    rcOperatorAccountService.insertSelective(operatorAccount);
                }else{
                    operatorAccount.setLastUpdatedTime(new Date());
                    operatorAccount.setLastUpdatedBy("admin");
                    operatorAccount.setAmount(amountTotal);
                    rcOperatorAccountService.updateByPrimaryKeySelective(operatorAccount);
                }
            }
        } catch (Exception e) {
            logger.error("----加盟商结算-定时任务----执行异常", e);
        } finally {
            logger.info(String.format("----加盟商结算-定时任务----执行完毕-耗时：%s 毫秒",(System.currentTimeMillis() - start)));
        }
    }
}
